<?php
namespace Libraries;
/**
 * 邮件发送类
 * created at 2016-04-25
 * @author 孙天相<suntianxiang@cjkt.com>
 * @package Libraries
 *
 * The class help you easy to send email from send_mail($email , $subject , $content);
 */
use \PHPMailer;
use Models\Config;

Class Mail {
	/**
	 *
	 * @var 邮件类
	 */
	private $mail;
	/**
	 * 配置
	 * @var 邮件配置信息
	 */
	private $config;
	/**
	 * 附件
	 * @var 附件数组
	 */
	private $attach;

	/**
	 * 发送邮件
	 * @param string $to 发送给谁
	 * @param string $subject 主题
	 * @param string $content 内容
	 * @param array  $attachs 附件
	 * @return bool
	 */
	public static function send($to,$subject,$content,$attachs = NULL){
		$mail = new PHPMailer(true);
		$configs = arr_key((new Config)->where('label', 'email')->get(), 'name');
		$mail->IsSMTP();
		$mail->CharSet = $configs['charset']['value']; //设置邮件的字符编码，这很重要，不然中文乱码
		$mail->SMTPAuth   = true;                  //开启认证
		$mail->Port       = $configs['port']['value'];
		$mail->SMTPSecure = "ssl";
		$mail->Host       = $configs['host']['value'];
		$mail->Username   = $configs['username']['value'];
		$mail->Password   = $configs['password']['value'];
		//$mail->IsSendmail(); //如果没有sendmail组件就注释掉，否则出现“Could  not execute: /var/qmail/bin/sendmail ”的错误提示
		$mail->AddReplyTo($configs['username']['value'],$configs['username']['value']);//回复地址
		$mail->From       = $configs['username']['value'];
		$mail->FromName   = $configs['username']['value'];
		$mail->WordWrap   = 100; // 设置每行字符串的长度
		$mail->IsHTML(true);

		$mail->AddAddress($to);
		$mail->Subject  = $subject;
		$mail->Body = $content;

		if($attachs && is_array($attachs) && count($attachs)>0){
			foreach ($attachs as $key => $value) {
				if(file_exists($value)){
					$mail->AddAttachment($value);
				} else {
					log_message('error' , "file: {$value} not exist!");
				}
			}
		}

		return $mail->Send();
	}


}
